import {
  Controller,
  Get,
  Post,
  Body,
  UseGuards,
  Headers,
  Param,
  UploadedFile,
  UseInterceptors,
  Response,
  StreamableFile,
  HttpStatus,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response as ExpressResponse } from 'express';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiParam,
  ApiQuery,
  ApiTags,
} from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';

import FileService from './service';
import { GetFileDetailType, UploadFileDto, UploadFileResponse } from './dto';

@ApiTags('file')
@Controller('/file')
export default class FileController {
  constructor(private readonly service: FileService) {}

  // @UseGuards(AuthGuard())
  @ApiOperation({
    summary: '文件上传',
  })
  @ApiResponse({
    type: UploadFileResponse,
  })
  @ApiBearerAuth()
  @Post('/upload')
  @UseInterceptors(FileInterceptor('file'))
  async upload(
    @UploadedFile() file: UploadFileDto,
  ): Promise<UploadFileResponse> {
    return this.service.upload(file);
  }

  @ApiOperation({
    summary: '查看某个文件(stream)',
  })
  @ApiParam({
    name: 'id',
    description: '文件id',
  })
  @ApiBearerAuth()
  @Get('/:id')
  async detail(
    @Param('id') id: string,
    @Response() res: ExpressResponse,
  ): Promise<void> {
    const detail: GetFileDetailType = await this.service.detail(id);

    if (detail.mime) {
      res.status(200).type(detail.mime).send(detail.buffer);
    } else {
      res.status(HttpStatus.BAD_REQUEST).json(detail);
    }
  }
}
